import argparse
import os
import cv2
import torch

from mmdet.apis import inference_detector, init_detector

# file_path=file
#
# dir_path=os.path.dirname(file_path)

#default_video_path=os.path.join(dir_path,'result.mp4') #定义的输出，默认是和video.py同目录的文件
default_video_path='video_data/work_dirs/output_video/result.mp4'


def parse_args():
    parser = argparse.ArgumentParser(description='MMDetection webcam demo')
    parser.add_argument('config', help='test config file path')
    parser.add_argument('checkpoint', help='checkpoint file')
    parser.add_argument(
    '--device', type=str, default='cuda:0', help='CPU/CUDA device option')
    parser.add_argument(
    '--file', type=str, help='test video path')#输入视频从哪输入
    parser.add_argument(
    '--out', type=str, default=default_video_path, help='bbox score threshold')#输出视频从哪输出
    parser.add_argument(
    '--camera-id', type=int, default=0, help='camera device id')
    parser.add_argument(
    '--score-thr', type=float, default=0.5, help='bbox score threshold')
    args = parser.parse_args()
    return args

def main():
    args = parse_args()

    device = torch.device(args.device)

    model = init_detector(args.config, args.checkpoint, device=device)

    camera = cv2.VideoCapture(args.file)#把这个地方换成视频位置，就不会调用摄像头了

    capture=cv2.VideoCapture(args.file)#希望输入视频和输出视频宽高一致
    width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))#获得源视频宽高
    height=int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))

    fps =capture.get(cv2.CAP_PROP_FPS)#获得帧数
    fourcc=cv2.VideoWriter_fourcc('M','P','4','2')

    video_writer=cv2.VideoWriter(args.out,fourcc,fps,(width,height))
    #out是保存视频的位置；保存的格式，MP4v；帧数；宽、高；

    print('Press "Esc", "q" or "Q" to exit.')
    while True:#无限循环，一帧一帧的读取，一秒24帧
        ret_val, img = camera.read()#返回bool值，读取成功就是ture
        print (img)
        result = inference_detector(model, img)

        ch = cv2.waitKey(1)
        if ch == 27 or ch == ord('q') or ch == ord('Q'): #27对应键盘上Esc这个键，ord()对应chr()这个函数，在里面传入Q，就会输出对应的ASCIK码
            break

        model.show_result(
            img, result, score_thr=args.score_thr, wait_time=1, show=True)

if __name__ == '__main__':
    main()